package com.douding.file.controller.admin;

import com.douding.server.domain.File;
import com.douding.server.domain.Test;
import com.douding.server.dto.FileDto;
import com.douding.server.dto.ResponseDto;
import com.douding.server.enums.FileUseEnum;
import com.douding.server.enums.YesNoEnum;
import com.douding.server.service.FileService;
import com.douding.server.service.TestService;
import com.douding.server.util.Base64ToMultipartFile;
import com.douding.server.util.UuidUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/*
    返回json 应用@RestController
    返回页面  用用@Controller
 */
@RequestMapping("/admin/file")
@RestController
public class UploadController {

    private static final Logger LOG = LoggerFactory.getLogger(UploadController.class);
    public  static final String BUSINESS_NAME ="文件上传";
    @Resource
    private TestService testService;

    @Value("${file.path}")
    private String FILE_PATH;

    @Value("${file.domain}")
    private String FILE_DOMAIN;

    @Resource
    private FileService fileService;

    /**
     * 上传照片
     * @param fileDto
     * @return
     * @throws Exception
     */
    @RequestMapping("/upload")
    public ResponseDto upload(@RequestBody FileDto fileDto) throws Exception {
        MultipartFile multipartFile = Base64ToMultipartFile.base64ToMultipart(fileDto.getShard());
        String token = UUID.randomUUID().toString().replace("-","").substring(8);
        System.out.println(FILE_PATH+token+fileDto.getName());
        java.io.File file = new java.io.File(FILE_PATH);
        if(!file.exists()){
            file.mkdirs();
            System.out.println("文件夹创建成功");
        }
        multipartFile.transferTo(new java.io.File(FILE_PATH+token+"_"+fileDto.getName()));
        fileDto.setPath("/f/"+token+"_"+fileDto.getName());
        fileService.save(fileDto);
        ResponseDto<Object> responseDto = new ResponseDto<>();
        responseDto.setContent(fileDto);
        return responseDto;
    }

    //合并分片
    public void merge(FileDto fileDto) throws Exception {
        LOG.info("合并分片开始");

    }

    /**
     * 检查本地是否有该照片
     * @param key
     * @return
     * @throws Exception
     */
    @GetMapping("/check/{key}")
    public ResponseDto check(@PathVariable String key) throws Exception {
        LOG.info("检查上传分片开始：{}", key);
//        File file = fileService.selectByKey(key);
        ResponseDto responseDto = new ResponseDto();
//        if(file!=null){
            responseDto.setSuccess(true);
//        }
        return responseDto;
    }

}//end class
